package com.github.caijh.mall.store.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.caijh.commons.util.Collections;
import com.github.caijh.commons.util.DateUtils;
import com.github.caijh.mall.store.dao.StoreProductCouponDao;
import com.github.caijh.mall.store.model.StoreProduct;
import com.github.caijh.mall.store.model.StoreProductCoupon;
import com.github.caijh.mall.store.service.StoreProductCouponService;
import org.springframework.stereotype.Service;

@Service
public class StoreProductCouponServiceImpl extends ServiceImpl<StoreProductCouponDao, StoreProductCoupon>
        implements StoreProductCouponService {

    @Resource
    private StoreProductCouponDao dao;

    /**
     * 删除商品的优惠券.
     *
     * @param productId 产品id
     */
    @Override
    public void deleteByProductId(Integer productId) {
        LambdaQueryWrapper<StoreProductCoupon> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreProductCoupon::getProductId, productId);
        dao.delete(lambdaQueryWrapper);
    }

    /**
     * 删除旧的优惠券，保存新的优惠券.
     *
     * @param storeProduct 商品
     * @param couponIds    优惠券ids
     */
    @Override
    public void updateProductCoupons(StoreProduct storeProduct, Collection<Integer> couponIds) {
        if (Collections.isNotEmpty(couponIds)) {
            this.deleteByProductId(storeProduct.getId());
            List<StoreProductCoupon> coupons = couponIds
                    .stream()
                    .map(couponId -> new StoreProductCoupon(storeProduct.getId(), couponId, ((int) DateUtils.currentTimestamp()))).collect(Collectors.toList());
            this.saveBatch(coupons);
        }
    }

    /**
     * 根据商品id获取已关联优惠券信息
     *
     * @param productId 商品id
     * @return 已关联优惠券
     */
    @Override
    public List<StoreProductCoupon> listByProductId(Integer productId) {
        LambdaQueryWrapper<StoreProductCoupon> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreProductCoupon::getProductId, productId);
        return dao.selectList(lambdaQueryWrapper);
    }

}

